package com.edwin.websitebe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edwin.websitebe.mapper.NewsMapper;
import com.edwin.websitebe.model.News;
import com.edwin.websitebe.service.NewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {

    @Override
    public boolean saveOrUpdate(News entity) {
        LocalDateTime now = LocalDateTime.now();
        if (Objects.isNull(entity.getId())) {
            entity.setCreateTime(now);
        }
        entity.setUpdateTime(now);
        return super.saveOrUpdate(entity);
    }

    @Override
    public Page<News> pageList(News news) {
        LambdaQueryWrapper<News> wrapper = new QueryWrapper<News>().lambda()
                .like(StringUtils.isNotEmpty(news.getNewsTitle()), News::getNewsTitle, news.getNewsTitle())
                .orderByAsc(News::getSort)
                .orderByDesc(News::getIsTop)
                .orderByDesc(News::getCreateTime);
        return this.page(Page.of(news.getPage(), news.getPageSize()), wrapper);
    }
}
